import 'package:flutter/material.dart';
import 'package:drift/drift.dart' as drift;
import 'database/database.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Drift数据库测试',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
        useMaterial3: true,
      ),
      home: const DatabaseTestPage(),
    );
  }
}

class DatabaseTestPage extends StatefulWidget {
  const DatabaseTestPage({super.key});

  @override
  State<DatabaseTestPage> createState() => _DatabaseTestPageState();
}

class _DatabaseTestPageState extends State<DatabaseTestPage> {
  late AppDatabase _database;
  List<User> _users = [];
  List<Task> _tasks = [];
  List<UserWithTasks> _usersWithTasks = [];

  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _taskTitleController = TextEditingController();
  final TextEditingController _taskDescriptionController =
      TextEditingController();

  // 事务测试相关状态
  String _transactionResult = '';
  bool _isTransactionRunning = false;

  @override
  void initState() {
    super.initState();
    _initDatabase();
  }

  Future<void> _initDatabase() async {
    _database = AppDatabase();
    await _loadData();
  }

  Future<void> _loadData() async {
    final users = await _database.getAllUsers();
    final tasks = await _database.getAllTasks();
    final usersWithTasks = await _database.getUsersWithTasks();

    setState(() {
      _users = users;
      _tasks = tasks;
      _usersWithTasks = usersWithTasks;
    });
  }

  Future<void> _addUser() async {
    if (_nameController.text.isEmpty || _emailController.text.isEmpty) {
      _showSnackBar('请输入姓名和邮箱');
      return;
    }

    final user = UsersCompanion(
      name: drift.Value(_nameController.text),
      email: drift.Value(_emailController.text),
    );

    await _database.insertUser(user);
    _nameController.clear();
    _emailController.clear();
    await _loadData();
    _showSnackBar('用户添加成功');
  }

  Future<void> _addTask(int userId) async {
    if (_taskTitleController.text.isEmpty) {
      _showSnackBar('请输入任务标题');
      return;
    }

    final task = TasksCompanion(
      title: drift.Value(_taskTitleController.text),
      description: drift.Value(_taskDescriptionController.text.isEmpty
          ? null
          : _taskDescriptionController.text),
      userId: drift.Value(userId),
    );

    await _database.insertTask(task);
    _taskTitleController.clear();
    _taskDescriptionController.clear();
    await _loadData();
    _showSnackBar('任务添加成功');
  }

  Future<void> _toggleTaskCompletion(Task task) async {
    final updatedTask = task.copyWith(
      isCompleted: !task.isCompleted,
      updatedAt: DateTime.now(),
    );

    await _database.updateTask(TasksCompanion(
      id: drift.Value(task.id),
      isCompleted: drift.Value(updatedTask.isCompleted),
      updatedAt: drift.Value(updatedTask.updatedAt),
    ));

    await _loadData();
  }

  Future<void> _deleteUser(int userId) async {
    await _database.deleteTasksByUserId(userId);
    await _database.deleteUser(userId);
    await _loadData();
    _showSnackBar('用户删除成功');
  }

  Future<void> _deleteTask(int taskId) async {
    await _database.deleteTask(taskId);
    await _loadData();
    _showSnackBar('任务删除成功');
  }

  // ========== 事务测试方法 ==========

  Future<void> _runTransactionTest(
      Future<String> Function() testFunction, String testName) async {
    setState(() {
      _isTransactionRunning = true;
      _transactionResult = '正在执行$testName...';
    });

    try {
      final result = await testFunction();
      setState(() {
        _transactionResult = '$testName结果：\n$result';
        _isTransactionRunning = false;
      });
      await _loadData(); // 重新加载数据以显示事务结果
    } catch (e) {
      setState(() {
        _transactionResult = '$testName执行失败：$e';
        _isTransactionRunning = false;
      });
    }
  }

  Future<void> _testBatchInsertTransaction() async {
    await _runTransactionTest(
      () => _database.testBatchInsertTransaction(),
      '批量插入事务测试',
    );
  }

  Future<void> _testTransferTransaction() async {
    await _runTransactionTest(
      () => _database.testTransferTransaction(),
      '转账事务测试',
    );
  }

  Future<void> _testRollbackTransaction() async {
    await _runTransactionTest(
      () => _database.testRollbackTransaction(),
      '回滚事务测试',
    );
  }

  Future<void> _testNestedTransaction() async {
    await _runTransactionTest(
      () => _database.testNestedTransaction(),
      '嵌套事务测试',
    );
  }

  Future<void> _testConditionalTransaction(bool shouldCommit) async {
    await _runTransactionTest(
      () => _database.testConditionalTransaction(shouldCommit),
      '条件事务测试 (shouldCommit=$shouldCommit)',
    );
  }

  Future<void> _testConcurrentTransactions() async {
    await _runTransactionTest(
      () => _database.testConcurrentTransactions(),
      '并发事务测试',
    );
  }

  Future<void> _testDataConsistency() async {
    await _runTransactionTest(
      () => _database.testDataConsistency(),
      '数据一致性检查',
    );
  }

  void _showSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message)),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text('Drift数据库测试'),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 添加用户区域
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '添加用户',
                      style:
                          TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 8),
                    TextField(
                      controller: _nameController,
                      decoration: const InputDecoration(
                        labelText: '姓名',
                        border: OutlineInputBorder(),
                      ),
                    ),
                    const SizedBox(height: 8),
                    TextField(
                      controller: _emailController,
                      decoration: const InputDecoration(
                        labelText: '邮箱',
                        border: OutlineInputBorder(),
                      ),
                    ),
                    const SizedBox(height: 8),
                    ElevatedButton(
                      onPressed: _addUser,
                      child: const Text('添加用户'),
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 添加任务区域
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '添加任务',
                      style:
                          TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 8),
                    TextField(
                      controller: _taskTitleController,
                      decoration: const InputDecoration(
                        labelText: '任务标题',
                        border: OutlineInputBorder(),
                      ),
                    ),
                    const SizedBox(height: 8),
                    TextField(
                      controller: _taskDescriptionController,
                      decoration: const InputDecoration(
                        labelText: '任务描述（可选）',
                        border: OutlineInputBorder(),
                      ),
                    ),
                    const SizedBox(height: 8),
                    if (_users.isNotEmpty) ...[
                      DropdownButtonFormField<int>(
                        decoration: const InputDecoration(
                          labelText: '选择用户',
                          border: OutlineInputBorder(),
                        ),
                        items: _users.map((user) {
                          return DropdownMenuItem(
                            value: user.id,
                            child: Text('${user.name} (${user.email})'),
                          );
                        }).toList(),
                        onChanged: (userId) {
                          if (userId != null) {
                            _addTask(userId);
                          }
                        },
                      ),
                    ] else ...[
                      const Text('请先添加用户',
                          style: TextStyle(color: Colors.grey)),
                    ],
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 用户和任务列表
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '用户和任务列表',
                      style:
                          TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 16),
                    if (_usersWithTasks.isEmpty)
                      const Center(
                        child: Text(
                          '暂无数据，请添加用户和任务',
                          style: TextStyle(color: Colors.grey),
                        ),
                      )
                    else
                      ..._usersWithTasks.map((userWithTasks) {
                        return ExpansionTile(
                          title: Text(
                            '${userWithTasks.user.name} (${userWithTasks.user.email})',
                            style: const TextStyle(fontWeight: FontWeight.bold),
                          ),
                          subtitle: Text(
                              '创建时间: ${userWithTasks.user.createdAt.toString().substring(0, 19)}'),
                          trailing: IconButton(
                            icon: const Icon(Icons.delete, color: Colors.red),
                            onPressed: () => _deleteUser(userWithTasks.user.id),
                          ),
                          children: [
                            if (userWithTasks.tasks.isEmpty)
                              const Padding(
                                padding: EdgeInsets.all(16.0),
                                child: Text('该用户暂无任务',
                                    style: TextStyle(color: Colors.grey)),
                              )
                            else
                              ...userWithTasks.tasks.map((task) {
                                return ListTile(
                                  title: Text(
                                    task.title,
                                    style: TextStyle(
                                      decoration: task.isCompleted
                                          ? TextDecoration.lineThrough
                                          : null,
                                    ),
                                  ),
                                  subtitle: task.description != null
                                      ? Text(task.description!)
                                      : null,
                                  trailing: Row(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      Checkbox(
                                        value: task.isCompleted,
                                        onChanged: (_) =>
                                            _toggleTaskCompletion(task),
                                      ),
                                      IconButton(
                                        icon: const Icon(Icons.delete,
                                            color: Colors.red),
                                        onPressed: () => _deleteTask(task.id),
                                      ),
                                    ],
                                  ),
                                );
                              }).toList(),
                          ],
                        );
                      }).toList(),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 事务测试区域
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '事务测试',
                      style:
                          TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 16),

                    // 事务测试按钮网格
                    Wrap(
                      spacing: 8.0,
                      runSpacing: 8.0,
                      children: [
                        ElevatedButton(
                          onPressed: _isTransactionRunning
                              ? null
                              : _testBatchInsertTransaction,
                          child: const Text('批量插入事务'),
                        ),
                        ElevatedButton(
                          onPressed: _isTransactionRunning
                              ? null
                              : _testTransferTransaction,
                          child: const Text('转账事务'),
                        ),
                        ElevatedButton(
                          onPressed: _isTransactionRunning
                              ? null
                              : _testRollbackTransaction,
                          child: const Text('回滚事务'),
                        ),
                        ElevatedButton(
                          onPressed: _isTransactionRunning
                              ? null
                              : _testNestedTransaction,
                          child: const Text('嵌套事务'),
                        ),
                        ElevatedButton(
                          onPressed: _isTransactionRunning
                              ? null
                              : () => _testConditionalTransaction(true),
                          child: const Text('条件事务(成功)'),
                        ),
                        ElevatedButton(
                          onPressed: _isTransactionRunning
                              ? null
                              : () => _testConditionalTransaction(false),
                          child: const Text('条件事务(失败)'),
                        ),
                        ElevatedButton(
                          onPressed: _isTransactionRunning
                              ? null
                              : _testConcurrentTransactions,
                          child: const Text('并发事务'),
                        ),
                        ElevatedButton(
                          onPressed: _isTransactionRunning
                              ? null
                              : _testDataConsistency,
                          child: const Text('数据一致性'),
                        ),
                      ],
                    ),

                    const SizedBox(height: 16),

                    // 事务执行状态
                    if (_isTransactionRunning)
                      const Row(
                        children: [
                          SizedBox(
                            width: 16,
                            height: 16,
                            child: CircularProgressIndicator(strokeWidth: 2),
                          ),
                          SizedBox(width: 8),
                          Text('正在执行事务测试...'),
                        ],
                      ),

                    // 事务测试结果显示
                    if (_transactionResult.isNotEmpty) ...[
                      const SizedBox(height: 8),
                      Container(
                        width: double.infinity,
                        padding: const EdgeInsets.all(12.0),
                        decoration: BoxDecoration(
                          color: Colors.grey[100],
                          borderRadius: BorderRadius.circular(8.0),
                          border: Border.all(color: Colors.grey[300]!),
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            const Text(
                              '测试结果：',
                              style: TextStyle(fontWeight: FontWeight.bold),
                            ),
                            const SizedBox(height: 4),
                            Text(
                              _transactionResult,
                              style: const TextStyle(fontSize: 12),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 统计信息
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '统计信息',
                      style:
                          TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 8),
                    Text('总用户数: ${_users.length}'),
                    Text('总任务数: ${_tasks.length}'),
                    Text(
                        '已完成任务: ${_tasks.where((task) => task.isCompleted).length}'),
                    Text(
                        '未完成任务: ${_tasks.where((task) => !task.isCompleted).length}'),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _database.close();
    _nameController.dispose();
    _emailController.dispose();
    _taskTitleController.dispose();
    _taskDescriptionController.dispose();
    super.dispose();
  }
}
